package com.ruoyi.project.system.exam.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.project.system.exam.service.IPkBattleService;
import com.ruoyi.project.system.partymember.domain.PartyMember;
import com.ruoyi.project.system.partymember.service.IPartyMemberService;
import com.ruoyi.project.system.partymember.service.impl.PartyMemberServiceImpl;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.exam.domain.PkBattle;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.project.system.question.domain.ExamDetail;
import com.ruoyi.project.system.question.domain.ExamRecord;
import com.ruoyi.project.system.question.domain.Question;
import com.ruoyi.project.system.question.service.IExamDetailService;
import com.ruoyi.project.system.question.service.IExamRecordService;
import com.ruoyi.project.system.question.service.IQuestionService;

/**
 * PK对战Controller
 * 
 * @author ruoyi
 * @date 2023-07-16
 */
@Controller
@RequestMapping("/system/exam/pk")
public class PkBattleController extends BaseController
{
    private String prefix = "system/exam/pk";

    @Autowired
    private IPkBattleService pkBattleService;

    @Autowired
    private IPartyMemberService partyMemberService;

    @Autowired
    private IExamRecordService examRecordService;
    
    @Autowired
    private IExamDetailService examDetailService;
    
    @Autowired
    private IQuestionService questionService;
    
    /**
     * 跳转到PK答题页面
     */
    @RequiresPermissions("system:exam:pk:index")
    @GetMapping()
    public String pk(ModelMap mmap)
    {
        // 获取当前登录用户的ID
        Long userId = getUserId();
        mmap.put("userId", userId);
        return prefix + "/pk";
    }

    /**
     * 跳转到PK答题页面
     */
    @RequiresPermissions("system:exam:pk:index")
    @GetMapping("/exam")
    public String exam(Long battleId, ModelMap mmap)
    {
        // 获取当前登录用户的ID
        Long userId = getUserId();
        mmap.put("userId", userId);
        mmap.put("battleId", battleId);
        return prefix + "/exam";
    }

    /**
     * 查询PK对战列表
     */
    @RequiresPermissions("system:exam:pk:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PkBattle pkBattle) {
        logger.info("查询PK对战列表，参数: {}", pkBattle);
        
        Long userId = getUserId();
        logger.info("当前用户ID: {}", userId);
        
        // 查询对应的绑定党员id
        PartyMember partyMember = partyMemberService.selectPartyMemberByUserId(userId);
        if (partyMember == null) {
            logger.warn("未找到当前用户的党员信息");
            return getDataTable(new ArrayList<>()); // 返回空列表
        }
        logger.info("找到党员信息，党员ID: {}", partyMember.getId());
        
        List<PkBattle> result = new ArrayList<>();
        
        // 1. 查询用户是挑战者但未答完题的列表
        PkBattle challengerCondition = new PkBattle();
        challengerCondition.setChallengerId(partyMember.getId());
        List<PkBattle> challengerList = pkBattleService.selectPkBattleList(challengerCondition);
        logger.info("查询到用户作为挑战者的对战数量: {}", challengerList.size());
        
        // 过滤挑战者未答完题的记录
        challengerList = challengerList.stream()
                .filter(battle -> 
                    // 对战状态为进行中(2)且挑战者未答题(0)或未设置
                    battle.getBattleStatus() == 2 && 
                    (battle.getChallengerAnswered() == null || battle.getChallengerAnswered() == 0))
                .collect(Collectors.toList());
        logger.info("过滤后用户作为挑战者且未答完题的对战数量: {}", challengerList.size());
        
        result.addAll(challengerList);
        
        // 2. 查询用户是发起者但未答完题的列表
        PkBattle initiatorCondition = new PkBattle();
        initiatorCondition.setInitiatorId(partyMember.getId());
        List<PkBattle> initiatorList = pkBattleService.selectPkBattleList(initiatorCondition);
        logger.info("查询到用户作为发起者的对战数量: {}", initiatorList.size());
        
        // 过滤发起者未答完题的记录
        initiatorList = initiatorList.stream()
                .filter(battle -> 
                    // 对战状态为进行中(2)且发起者未答题(0)或未设置
                    battle.getBattleStatus() == 2 && 
                    (battle.getInitiatorAnswered() == null || battle.getInitiatorAnswered() == 0))
                .collect(Collectors.toList());
        logger.info("过滤后用户作为发起者且未答完题的对战数量: {}", initiatorList.size());
        
        result.addAll(initiatorList);
        
        // 去重处理（防止同一记录既是发起者又是挑战者的情况，虽然理论上不会出现）
        result = result.stream().distinct().collect(Collectors.toList());
        logger.info("合并后的对战列表总数: {}", result.size());
        
        return getDataTable(result);
    }

    /**
     * 查询已完成的PK对战列表
     */
    @RequiresPermissions("system:exam:pk:list")
    @PostMapping("/finishedList")
    @ResponseBody
    public TableDataInfo finishedList(PkBattle pkBattle) {
        logger.info("查询已完成的PK对战列表，参数: {}", pkBattle);


        Long userId = getUserId();
        logger.info("未指定查询条件，使用当前用户ID: {}", userId);

        // 查询对应的绑定党员id
        PartyMember partyMember = partyMemberService.selectPartyMemberByUserId(userId);
        // 查询作为发起者的
        PkBattle pkBattle1 = new PkBattle();
        pkBattle1.setInitiatorId(partyMember.getId());
        pkBattle1.setInitiatorAnswered(1);
        List<PkBattle> list = pkBattleService.selectFinishedPkBattleList(pkBattle1);

        // 查询作为挑战者的
        PkBattle pkBattle2 = new PkBattle();
        pkBattle2.setChallengerId(partyMember.getId());
        pkBattle2.setChallengerAnswered(1);
        List<PkBattle> list1 = pkBattleService.selectFinishedPkBattleList(pkBattle2);
        list1.addAll( list);

        logger.info("查询结果数量: {}", list1.size());
        return getDataTable(list1);
    }

    /**
     * 根据用户ID查询PK对战列表
     */
    @RequiresPermissions("system:exam:pk:list")
    @PostMapping("/listByUser")
    @ResponseBody
    public TableDataInfo listByUser()
    {
        Long userId = getUserId();
        // 党员id
        Long partyMemberId = partyMemberService.selectPartyMemberByUserId(userId).getId();
        logger.info("查询用户ID为{}的PK对战列表", userId);
        List<PkBattle> list = pkBattleService.selectPkBattleByUserId(partyMemberId);
        // 过滤出挑战者是当前用户且状态为等待应战的记录
        list = list.stream()
                .filter(battle -> 
                    // 对战状态为等待应战且当前用户是挑战者
                    battle.getBattleStatus() == 1 && (battle.getChallengerId() != null && battle.getChallengerId().equals(partyMemberId)))
                .collect(Collectors.toList());
        return getDataTable(list);
    }

    /**
     * 导出PK对战列表
     */
    @RequiresPermissions("system:exam:pk:export")
    @Log(title = "PK对战", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(PkBattle pkBattle)
    {
        List<PkBattle> list = pkBattleService.selectPkBattleList(pkBattle);
        ExcelUtil<PkBattle> util = new ExcelUtil<PkBattle>(PkBattle.class);
        return util.exportExcel(list, "PK对战数据");
    }

    /**
     * 新增PK对战
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        // 获取当前登录用户对应的党员信息
        Long userId = getUserId();
        PartyMember currentUserPartyMember = partyMemberService.selectPartyMemberByUserId(userId);
        mmap.put("currentUserPartyMember", currentUserPartyMember);
        return prefix + "/add";
    }

    /**
     * 新增保存PK对战
     */
    @RequiresPermissions("system:exam:pk:add")
    @Log(title = "PK对战", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(PkBattle pkBattle)
    {
        // 设置创建者为当前登录用户
        pkBattle.setCreateBy(getLoginName());
        return toAjax(pkBattleService.insertPkBattle(pkBattle));
    }

    /**
     * 修改PK对战
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        PkBattle pkBattle = pkBattleService.selectPkBattleById(id);
        mmap.put("pkBattle", pkBattle);
        return prefix + "/edit";
    }

    /**
     * 修改保存PK对战
     */
    @RequiresPermissions("system:exam:pk:edit")
    @Log(title = "PK对战", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(PkBattle pkBattle)
    {
        return toAjax(pkBattleService.updatePkBattle(pkBattle));
    }

    /**
     * 删除PK对战
     */
    @RequiresPermissions("system:exam:pk:remove")
    @Log(title = "PK对战", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(pkBattleService.deletePkBattleByIds(Convert.toLongArray(ids)));
    }
    
    /**
     * 查看PK对战详情
     */
    @RequiresPermissions("system:exam:pk:view")
    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id, ModelMap mmap)
    {
        PkBattle pkBattle = pkBattleService.selectPkBattleById(id);
        mmap.put("pkBattle", pkBattle);
        return prefix + "/view";
    }
    
    /**
     * 检查当前用户是否关联了党员信息
     */
    @GetMapping("/checkPartyMember")
    @ResponseBody
    public AjaxResult checkPartyMember() {
        Long userId = getUserId();
        PartyMember partyMember = partyMemberService.selectPartyMemberByUserId(userId);
        if (partyMember == null) {
            return AjaxResult.error("当前用户未关联党员信息，请联系管理员进行关联");
        }
        return AjaxResult.success();
    }
    
    /**
     * 接受挑战
     */
    @RequiresPermissions("system:exam:pk:accept")
    @PostMapping("/accept/{battleId}")
    @ResponseBody
    public AjaxResult acceptChallenge(@PathVariable("battleId") Long battleId) {
        try {
            // 获取当前登录用户信息
            Long userId = getUserId();
            PartyMember currentPartyMember = partyMemberService.selectPartyMemberByUserId(userId);
            
            if (currentPartyMember == null) {
                return AjaxResult.error("当前用户未关联党员信息，请联系管理员进行关联");
            }
            
            // 查询对战信息
            PkBattle pkBattle = pkBattleService.selectPkBattleById(battleId);
            if (pkBattle == null) {
                return AjaxResult.error("对战信息不存在");
            }
            
            // 检查对战状态是否为等待应战
            if (pkBattle.getBattleStatus() != 1) {
                return AjaxResult.error("该对战不在等待应战状态");
            }
            
            // 检查是否是自己发起的对战
            if (pkBattle.getInitiatorId().equals(currentPartyMember.getId())) {
                return AjaxResult.error("不能接受自己发起的挑战");
            }
            
            // 更新对战信息
            pkBattle.setChallengerId(currentPartyMember.getId());
            pkBattle.setBattleStatus(2); // 设置为对战中状态
            pkBattle.setStartTime(new Date()); // 设置开始时间
            
            // 更新对战信息
            pkBattleService.updatePkBattle(pkBattle);
            
            return AjaxResult.success("挑战接受成功", battleId);
        } catch (Exception e) {
            logger.error("接受挑战失败", e);
            return AjaxResult.error("接受挑战失败，请重试");
        }
    }
    
    /**
     * 提交PK答题答案
     */
    @RequiresPermissions("system:exam:pk:index")
    @PostMapping("/submitAnswer/{battleId}")
    @ResponseBody
    public AjaxResult submitAnswer(@PathVariable("battleId")Long battleId, @RequestBody Map<String, String> answers) {
        try {
            // 获取当前用户ID
            Long userId = getUserId();
            PartyMember currentUserPartyMember = partyMemberService.selectPartyMemberByUserId(userId);
            Long partyMemberId = currentUserPartyMember.getId();
            
            // 查询对战信息
            PkBattle pkBattle = pkBattleService.selectPkBattleById(battleId);
            if (pkBattle == null) {
                return AjaxResult.error("对战信息不存在");
            }

            
            // 检查对战状态是否为进行中
            if (pkBattle.getBattleStatus() != 2) {
                return AjaxResult.error("该对战不在进行中状态");
            }
            
            // 处理每一道题的答案
            int correctCount = 0;
            for (Map.Entry<String, String> entry : answers.entrySet()) {
                Long questionId = Long.valueOf(entry.getKey());
                String userAnswer = entry.getValue();
                
                // 查询题目信息
                Question question = questionService.selectQuestionById(questionId);
                if (question == null) {
                    logger.warn("题目信息不存在: questionId={}", questionId);
                    continue;
                }
                
                // 判断答案是否正确
                int isCorrect = 0;
                if (question.getQuestionType() == 4) { // 填空题
                    // 填空题答案比较（忽略大小写和空格）
                    if (userAnswer != null && userAnswer.trim().toLowerCase().equals(
                            (question.getCorrectAnswer() != null ? question.getCorrectAnswer() : "").trim().toLowerCase())) {
                        isCorrect = 1;
                        correctCount++;
                    }
                } else {
                    // 其他题型答案比较
                    if (userAnswer != null && userAnswer.equals(question.getCorrectAnswer())) {
                        isCorrect = 1;
                        correctCount++;
                    }
                }
                
                // 创建答题详情记录
                ExamDetail detail = new ExamDetail();
                detail.setRecordId(battleId); // 使用battleId作为recordId关联
                detail.setQuestionId(questionId);
                detail.setUserAnswer(userAnswer);
                detail.setIsCorrect(isCorrect); // 根据答案判断是否正确
                examDetailService.insertExamDetail(detail);
            }
            
            // 更新用户答题状态
            if (partyMemberId.equals(pkBattle.getInitiatorId())) {
                // 发起者答题
                pkBattle.setInitiatorAnswered(1);
            } else {
                // 挑战者答题
                pkBattle.setChallengerAnswered(1);
            }
            
            // 检查是否双方都已完成答题
            if (pkBattle.getInitiatorAnswered() != null && pkBattle.getInitiatorAnswered() == 1 
                    && pkBattle.getChallengerAnswered() != null && pkBattle.getChallengerAnswered() == 1) {
                // 双方都已完成答题，更新对战状态为已完成
                pkBattle.setBattleStatus(3); // 已结束
                pkBattle.setEndTime(new Date()); // 设置结束时间
                pkBattle.setWinnerId(pkBattle.getInitiatorAnswered() > pkBattle.getChallengerAnswered() ? pkBattle.getInitiatorId() : pkBattle.getChallengerId());
            }
            
            // 更新对战信息
            pkBattleService.updatePkBattle(pkBattle);
            
            // 返回正确题数
            Map<String, Object> result = new HashMap<>();
            result.put("correctCount", correctCount);
            result.put("totalQuestions", answers.size());
            result.put("score", Math.round((float) correctCount / answers.size() * 100));
            
            return AjaxResult.success("答案提交成功", result);
        } catch (Exception e) {
            logger.error("提交答案失败", e);
            return AjaxResult.error("提交答案失败: " + e.getMessage());
        }
    }


}